import axios from 'axios'
import { AnyNotification } from '../components/AnyNotification'

// 创建 axios 实例
const anyHttpClient = axios.create({
  baseURL: import.meta.env.VITE_API_BASE_URL || '',
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json'
  }
})

// 请求拦截器
anyHttpClient.interceptors.request.use(
  (config) => {
    // 添加认证 token
    const authToken = localStorage.getItem('token')
    if (authToken) {
      config.headers.Authorization = `Bearer ${authToken}`
    }

    console.log('AnyRequest sending:', config.method?.toUpperCase(), config.url)
    return config
  },
  (error) => {
    console.error('AnyRequest config error:', error)
    return Promise.reject(error)
  }
)

// 响应拦截器
anyHttpClient.interceptors.response.use(
  (response) => {
    const { data } = response

    // 统一处理业务状态码
    if (data && (data.code === 200 || data.success)) {
      return data
    } else if (data && data.code && data.code !== 200) {
      console.error('AnyRequest business error:', data.message)
      return Promise.reject(new Error(data.message || '请求失败'))
    } else {
      // 如果没有 code 字段，可能是直接返回的数据，直接返回
      return response
    }
  },
  (error) => {
    console.error('AnyRequest network error:', error)

    // 统一错误处理
    let errorMessage = '网络请求失败'
    if (error.response) {
      const { status, data } = error.response

            switch (status) {
        case 400:
          // 处理字段验证错误
          if (data && data.data && typeof data.data === 'object') {
            // 如果返回的是字段错误对象，显示具体的字段错误信息
            AnyNotification.validationError(data.data, data.message)
            errorMessage = data.message || '参数验证失败'
          } else {
            errorMessage = data?.message || '参数验证失败'
            AnyNotification.parameterError(errorMessage)
          }
          break
        case 401:
          AnyNotification.authError()
          errorMessage = '未授权，请重新登录'
          break
        case 403:
          AnyNotification.permissionError()
          errorMessage = '拒绝访问'
          break
        case 404:
          AnyNotification.notFoundError()
          errorMessage = '请求资源不存在'
          break
        case 500:
          AnyNotification.serverError()
          errorMessage = '服务器内部错误'
          break
        default:
          errorMessage = data?.message || '请求失败'
          if (errorMessage !== '请求失败') {
            AnyNotification.generalError(errorMessage)
          }
      }
    } else if (error.request) {
      errorMessage = '网络连接失败'
      AnyNotification.networkError()
    }

    return Promise.reject(new Error(errorMessage))
  }
)

// 导出便捷方法
export const anyGet = (url: string, params?: any) => {
  return anyHttpClient.get(url, { params })
}

export const anyPost = (url: string, data?: any) => {
  return anyHttpClient.post(url, data)
}

export const anyPut = (url: string, data?: any) => {
  return anyHttpClient.put(url, data)
}

export const anyDelete = (url: string) => {
  return anyHttpClient.delete(url)
}

export const anyPatch = (url: string, data?: any) => {
  return anyHttpClient.patch(url, data)
}

// 文件上传
export const anyUpload = (url: string, file: File) => {
  const formData = new FormData()
  formData.append('file', file)

  // 不要手动设置 Content-Type，让浏览器自动设置以包含 boundary
  return anyHttpClient.post(url, formData)
}

// 文件下载
export const anyDownload = async (url: string, params?: any, filename?: string) => {
  const response = await anyHttpClient.get(url, {
    params,
    responseType: 'blob'
  })

  const blob = new Blob([response.data])
  const downloadUrl = window.URL.createObjectURL(blob)
  const link = document.createElement('a')
  link.href = downloadUrl
  link.download = filename || 'download'
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
  window.URL.revokeObjectURL(downloadUrl)
}

// 导出实例
export { anyHttpClient }
export default anyHttpClient